package com.qf.web;

import com.qf.constant.Constant;
import com.qf.convert.MyConvert;
import com.qf.pojo.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import com.qf.utils.MD5Utils;
import com.qf.utils.UUIDUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;

/*
*
* 用户模块
* */
@WebServlet("/user")
public class UserServlet extends BaseServlet {


    /**
     * 前台跳转后台---请求转发/jsp/register.jsp
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void registerUI(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        //请求转发
        request.getRequestDispatcher("/jsp/register.jsp").forward(request,response);
    }

   /* //定义自己方法
    public void add(HttpServletRequest request,HttpServletResponse response) {
        System.out.println("add方法调用了") ;
    }*/

    /**
     * 校验用户名(异步请求服务器)
     * @param request
     * @param response
     * @throws IOException
     */
   public void checkUser(HttpServletRequest request,HttpServletResponse response) throws IOException {
       //接收参数
       String username = request.getParameter("username");
       // System.out.println(username);
       //调用业务层接口
       UserService userService = new UserServiceImpl() ;
       boolean flag = userService.checkUser(username) ;
       if(flag){
           //不能注册
           //服务器响应给浏览器
           response.getWriter().write("1");
       }else{
           //能注册
           response.getWriter().write("0");
       }
   }


    /**
     * 注册功能
     * @param request 请求
     * @param response 响应
     * @throws ServletException
     * @throws IOException
     */
   public void register(HttpServletRequest request,HttpServletResponse response)
           throws ServletException, IOException {

       //1)校验验证码
       //接收前台用户输入的验证码
       String usercode = request.getParameter("usercode");
       //获取服务器端存储的验证码
       //获取session
       HttpSession session = request.getSession();
       //从session域中服务器端存储的验证码
       String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
       //验证码必须一次性的,防止刷新了一张新的验证码,上一次的没有删除掉
       session.removeAttribute("CHECKCODE_SERVER");
       //用户没有填写验证码或者输入的验证码和服务器端的不一致
       if(usercode==null || !usercode.equalsIgnoreCase(checkcode_server)){
           //给request域中存储一个信息
           request.setAttribute("msg","验证码输入错误!");
           //请求转发了
           request.getRequestDispatcher("/jsp/msg.jsp").forward(request,response);

       }

       //接收用户的其他参数
       Map<String, String[]> map = request.getParameterMap();
       //创建User对象
       User user = new User()  ;
       //单独处理日期:前台提交日期是文本 String
       //BeanUtils.jar有一个工具类ConvertUtils :注册自定义转换器
       ConvertUtils.register(new MyConvert(), Date.class) ;

       //封装User中的所有数据
       //BeanUtils
       try {
           BeanUtils.populate(user,map);
       } catch (IllegalAccessException e) {
           e.printStackTrace();
       } catch (InvocationTargetException e) {
           e.printStackTrace();
       }


       //用户user的uid是生成的
       String uid = UUIDUtils.getId();
       user.setUid(uid);
       //密码使用工具类Md5utils工具类加密

       user.setPassword(MD5Utils.md5(user.getPassword()));
       //激活码code---UUID工具类生成的
       user.setCode(UUIDUtils.getCode()) ;

       System.out.println(user);

       //调用业务接口
       UserService userService = new UserServiceImpl() ;
       userService.registerUser(user) ;


       //给request设置一个消息提示
       request.setAttribute("msg","用户注册成功,请激活用户");
       request.getRequestDispatcher("/jsp/msg.jsp").forward(request,response);
   }


   public void active(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
       // http://localhost:8080/maven_study_02_war/user?methodName=active&code=FF174D187BB3444595B1D7AFA4DA9B8B
       //接收code这个参数
       String code = request.getParameter("code");
       //调用业务接口
       UserService userService = new UserServiceImpl() ;
       User user = userService.findUserByCode(code) ;

       //判断
       if(user!=null){
           //提示信息
           request.setAttribute("msg","用户激活成功,请<a href='/maven_study_02_war/user?methodName=loginUI'>登录</a>");
           //请求转发msg.jsp
           request.getRequestDispatcher("/jsp/msg.jsp").forward(request,response) ;
       }else{
           //提示信息
           request.setAttribute("msg","用户激活失败,请重新激活!");
           //请求转发msg.jsp
           request.getRequestDispatcher("/jsp/msg.jsp").forward(request,response) ;
       }

   }

    /**
     * 后台请求转发到前台的登录页面
     * @param request
     * @param response
     */
   public void loginUI(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
   }

    /**
     * 普通用户登录业务
     * @param request  请求对象
     * @param response  响应对象
     */
   public void login(HttpServletRequest request,HttpServletResponse response) throws Exception {

       //1)校验验证码
       //接收前台用户输入的验证码的参数loginCode
       String loginCode = request.getParameter("loginCode");
       //获取sesison中存储的后台的验证码
       HttpSession session = request.getSession();
       //从session取出服务器端存储的验证码
       String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
        //一次性验证
       session.removeAttribute("CHECKCODE_SERVER");

       //判断 没有输入验证码或者和服务器端验证码不一致
       if(loginCode ==null || !loginCode.equalsIgnoreCase(checkcode_server)){
           //错误信息提示
           request.setAttribute("msg","验证码输入有误") ;
           request.getRequestDispatcher("/jsp/msg.jsp").forward(request,response);
           return;
       }

       //2)接收用户名和密码的参数
       //username/password
       String username = request.getParameter("username");
       String password = request.getParameter("password");//"123456" 没有加密的

       //密码加密--在数据库中才能查询用户
       password =MD5Utils.md5(password) ;
       //调用业务接口
       UserService userService = new UserServiceImpl() ;
       User user = userService.findUserByUsernameAndPwd(username,password) ;

       //如果用户不存在
       if(user==null){
           request.setAttribute("msg","用户名或者密码输入错误") ;
           request.getRequestDispatcher("/jsp/msg.jsp").forward(request,response);
           return;
       }

       //用户存在了,判断用户的激活码是否为 1
       //不为1
       if(user.getState() != Constant.USER_ACTIVE_STATE){
           //错误提示
           request.setAttribute("msg","用户尚未激活,请先<a href='http://localhost:8080/maven_study_02_war/user?methodName=active&code="+user.getCode()+"'>激活</a>");
           request.getRequestDispatcher("/jsp/msg.jsp").forward(request,response);
           return;
       }

       //用户存在,并且state为1
       //将user对象 存储在session域中
       session.setAttribute("user",user) ;

       //自动登录
       //接收用户是否勾选了自动登录的参数
       //auto_user
       String auto_user = request.getParameter("auto_user");
       //判断是否勾选
       if(!"AutoUser".equals(auto_user)){
           //没有勾选
           //创建Cookie
           Cookie cookie = new Cookie("autouser","" );
           //设置有效期设置0,一会服务器响应浏览器,直接删除
           cookie.setMaxAge(0);
           response.addCookie(cookie); //发送浏览器
       }else{
          // 勾选了
           //将用户和密码拼接起立作为cookie的内容
           String content = user.getUsername()+":"+user.getPassword() ;
           //使用jdk加密工具URLEncoder
           content= URLEncoder.encode(content, "utf-8");

           //创建Cookie
           Cookie cookie = new Cookie("autouser",content) ;
           //设置有效期1个月
           cookie.setMaxAge(60*60*24*30) ;
           //服务器响应给浏览器
           response.addCookie(cookie);
       }


       //重定向到前台首页
       response.sendRedirect(request.getContextPath()+"/");




   }

}
